import datetime

from django.db import transaction
from django.db.models import Sum
from rest_framework import serializers
from rest_framework.serializers import ModelSerializer

from base.api.utils import update_customer_points, set_customer_vip
from finance.api.utils import update_account
from points.models import PointType, Recharge, PointConsume


class PointTypeSerializer(ModelSerializer):
    """
    积分类型
    """
    class Meta:
        model = PointType
        exclude = ["update_time", "add_time"]


class RechargeSerializer(ModelSerializer):
    """
    客户充值
    """
    customer_name = serializers.CharField(source='customer.name', read_only=True)
    status_name = serializers.CharField(source='get_status_display', read_only=True)
    user_name = serializers.CharField(source='user.real_name', read_only=True)
    account_name = serializers.CharField(source='account.name', read_only=True)

    class Meta:
        model = Recharge
        exclude = ["add_time"]

    def create(self, validated_data):
        with transaction.atomic():
            # 创建事务保存点
            save_id = transaction.savepoint()
            instance = None
            try:
                category = validated_data.get('category', 0)
                instance = self.Meta.model.objects.create(**validated_data)
                if category == 0:   # 充值
                    # 收款账号增加
                    update_account(instance.account_id, -1 * instance.money)
                    # 客户账号增加积分
                    update_customer_points(instance.customer_id, instance.active_point, instance.member_point)
                    if instance.money > 0:
                        set_customer_vip(instance)

            except Exception as e:
                print(e)
                transaction.savepoint_rollback(save_id)

            transaction.savepoint_commit(save_id)
        return instance

    def update(self, instance, validated_data):
        with transaction.atomic():
            # 创建事务保存点
            save_id = transaction.savepoint()
            try:
                instance.customer = validated_data.get('customer', instance.customer)
                instance.account = validated_data.get('account', instance.account)
                old_money = instance.money
                old_active_point = instance.active_point
                old_member_point = instance.member_point
                instance.money = validated_data.get('money', instance.money)
                instance.active_point = validated_data.get('active_point', instance.active_point)
                instance.member_point = validated_data.get('member_point', instance.member_point)
                instance.status = validated_data.get('status', instance.status)
                instance.remark = validated_data.get('remark', instance.remark)
                instance.user = validated_data.get('user', instance.user)

                instance.save()

                if instance.category == 0:      # 充值
                    # 收款账号修改
                    update_account(instance.account_id, old_money)
                    update_account(instance.account_id, -1 * instance.money)
                    # 客户账号修改积分
                    update_customer_points(instance.customer_id, -1 * old_active_point, -1 * old_member_point)
                    update_customer_points(instance.customer_id, instance.active_point, instance.member_point)

            except Exception as e:
                print(e)
                transaction.savepoint_rollback(save_id)

            transaction.savepoint_commit(save_id)

        return instance


class PointConsumeSerializer(ModelSerializer):
    """
    积分消费记录
    """

    customer_name = serializers.CharField(source='customer.name', read_only=True)
    cate_name = serializers.CharField(source='get_category_display', read_only=True)
    user_name = serializers.CharField(source='user.real_name', read_only=True)

    class Meta:
        model = PointConsume
        exclude = ["add_time"]


